/*
	Initalize application and knockout.js
*/

/* Variables */
var strCategory = "category";
var strSubCategory = "subcategory";
var strOverview = "overview";
var strBookDetail = "bookDetail";
var strSettingStart = "settingStart";
var strSettingBack = "setting";
var strSelectFolder = "strSelectFolder";
var stackViews = new Array();
var myScroll;	// Use for: About, Setting, Category & Sub-Category, Book (includes child pages)
var myScrollPager; // Use for: Overview
var myScrollStart; // User for: Start page
var folderScroll; // User for: Pop-over in Book page (Add favorite)
var isScrollByUser = true;
var lastTapTime;
var systemLanguage = "en";
var strDeviceId = "";
var timeStamp = 23696478300260;
var isLogin = false;
var startTab = "start";
var browseTab = "browse";
var favoriteTab = "favorite";
var settingTab = "setting";
var aboutTab = "about";
var spinner = {};
var topLocation = ($(document).height() - 300) / 2;
var minFontSize = 15;
var maxFontSize = 30;
var maxPageNumber = 20;
var pageBufferNumber = 2;
var maxItemsKeepOnList = 200;
var isLoading = false;
var isUserActionClick = true;
var strCatchFolder = "catchdata"; //Can't change this key
var isShowLoading = false;
var expireSessionCode = 2001;
var appVersionPrefix = "";

var strRefreshToken    = "";
var strAccessToken     = "";


// [iOS]
var lang;
var overviewListFromSubcategory = new Array();
// [BlackBerry]
var isOnlineInternetStatus = false;
var localPathForBB = "file:///accounts/1000/shared/misc/";

function onOnline() {
	isOnlineInternetStatus = true;
}

function onOffline() {
	isOnlineInternetStatus = false;
}


document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener('DOMContentLoaded', function () {
	setTimeout(loaded, 200);
}, false);

function loaded() {}

// Cordova is ready
function onDeviceReady() {

    if (!isDebug){
        console.log = function(){};
    }
	document.addEventListener("backbutton", onBackKeyDown, false);
    start();
}

var model;

/*
	Get device language and clear cache. Keep: domainkey, wasrated, firstStart
	+ Success: set localStore with new language
	+ Fail: set default language
	Begin Application
*/
function start() {
	if (isAndroid)
		startAndroid();
	if (isiOS)
		startiOS();
	if (isWP)
		startWP();
	if (isBB)
		startBB();
}

// Load languages and reset local storage
function startApp() {
	var previousLang = localStore.get("previousLang");
	if (previousLang != null && previousLang != systemLanguage) {
		showPopup(getLocalizeText('soSorryOsLanugage'));
		// [DONE]: move to new funcion
		ResetLocalStorage();
	} 
	localStore.save("previousLang", systemLanguage);
	beginApp();
}

// [ENHANCE] Can move seperate functions (for each OS) to app-config.js
// [ANDROID]
function startAndroid() {
	appVersionPrefix = "android_";
	navigator.globalization.getLocaleName(
		function (locale) {
			systemLanguage = locale.value.substring(0, 2);
			bookVM.reloadLanguage();
			startpageVM.reloadLanguage();
			startApp();
		},
		function () {
			beginApp();
		});
}

// [iOS]
function startiOS() {
	appVersionPrefix = "iOS_";
	/* move directory from tmp to document */
	lang = navigator.language.split("-");
	systemLanguage = (lang[0]);
    bookVM.reloadLanguage();
    startpageVM.reloadLanguage();
	localStore.moveCacheDirectory();
	startApp();
}

// [WP]
function startWP() {
	appVersionPrefix = "windows_";
	cordova.exec(
		function (resultString) {
			systemLanguage = resultString.substring(0, 2);
			bookVM.reloadLanguage();
			startpageVM.reloadLanguage();
			startApp();
		}, function (error) {
			setLanguageDefault();
			beginApp();
		}, "GATDevice"
		,	"languageCode"
		, ["getdeviceId"]);
}

// [BB]
function startBB() {
	appVersionPrefix = "bb_";
	lang = navigator.language.split("-");
	systemLanguage = (lang[0]);
	startApp();
}

/*
	Initialize knockout framework
	Bind models, get session
*/
function beginApp() {
	// Configure for knockout external template
	infuser.defaults.templatePrefix = "";
	infuser.defaults.templateSuffix = ".tpl.html";
	infuser.defaults.templateUrl = "template";
	infuser.defaults.ajax.async = true;
	infuser.defaults.ajax.cache = true;

	model = new VM();
	model.init();
	ko.applyBindings(model);
    
    /* check is login or not and made decision to next step */
    
    showDescriptionStartPageFirstTime();
    
    if (localStore.get(strIsLoginKey) != null) {
        isLogin = true;
        /* get access token and refresh token */
        strAccessToken  = localStore.get(strAccessTokenKey);
        strRefreshToken = localStore.get(strRefreshTokenKey);
        
        console.log(strAccessToken);
        model.favoriteVM.getFolders();
        model.homeVM.go();
    }

	// [BB]
	if (isBB){
		FlurryAgent.startSession('QB6K3HJ9X235S69JY8ST');
    }

	// Check for request ratting app (Open after 10 times and 2 months)
	var appStartupTimes = localStore.get("app_startup_times") == null ? 0 : parseInt(localStore.get("app_startup_times"), 10);
	if (appStartupTimes == 0) {
		localStore.save("app_startup_times", 2);
	} else if (appStartupTimes < 11) {
		localStore.save("app_startup_times", appStartupTimes + 1);
	} else {
		localStore.save("app_startup_times", 1);
		var currTapTime = new Date().getTime();
		var lastRating = localStore.get("wasrated") == null ? 0 : parseInt(localStore.get("wasrated"));
		if (currTapTime - lastRating > 5184000000) {
			navigator.notification.confirm(
				getLocalizeText('doYouWantRatingApp'), // message
				ratingApp, // callback to invoke with index of button pressed
				getLocalizeText('confirm'), // title
				getLocalizeText('ok') + ',' + getLocalizeText('cancel') // buttonLabels
			);
		}
	}
}

/*
	Redirect to Google play for rating
*/
function ratingApp(option) {
	var optionOk = 1;
	// [BB]
	if (isBB){
		optionOk = 0;
	}
	if (option == optionOk) {		
		var currTapTime = new Date().getTime();
		localStore.save("wasrated", currTapTime);
		// [ANDROID]
		if (isAndroid)
			window.open(encodeURI("https://play.google.com/store/apps/details?id=com.soxes.getAbstract&hl=en"), '_system', 'location=yes');
		// [iOS]
		if (isiOS)
			window.open(encodeURI("https://itunes.apple.com/us/app/getabstract/id338552990?mt=8"), '_system', 'location=yes');
		// [WP]
		if (isWP)
			window.open(encodeURI("http://www.windowsphone.com/en-us/store/app/getabstract/da97d352-e50f-4ee5-baca-2dfcf5596494"), '_system', 'location=yes');
		// [BB]
		if (isBB) {
			var langCode = "EN";
			if (lang.length > 1)
				langCode = lang[1];
			window.open(encodeURI("https://appworld.blackberry.com/webstore/content/40682/?countrycode=" + langCode + "&lang=" + systemLanguage), '_system', 'location=yes');
		}
	}
}

/* 
	Prevent multi-touch on screen
*/
function isJqmGhostClick(event) {
	if (!isUserActionClick) {
		isUserActionClick = true;
		return false;
	}
	
	var currTapTime = new Date().getTime();
	if (lastTapTime == null || currTapTime > (lastTapTime + 500)) {
		lastTapTime = currTapTime;
		if (event != undefined) {
			event();
		}
		console.log('accept click');
		return false;
	} else {
	    console.log('reject click');
		return true;
	}
}

/*
	Handle back key down
*/
function onBackKeyDown() {
	// [ENHANCE]: touch on Back button many times
	if (isLoading || isShowLoading) {
		return;
	}
	if (stackViews.length > 0) {
		backAction();
	} else {
		// [ANDROID] & [BB]
		if (isAndroid || isBB) {
			navigator.notification.confirm(
				getLocalizeText('doYouWantToExist'),
				function (option) {
					if (option == 1) {
						navigator.app.exitApp();
					}
				}, // callback to invoke with index of button pressed
				getLocalizeText('confirm'),
				getLocalizeText('yes') + ',' + getLocalizeText('no')
			);
		}
		// [WP]
		if (isWP)
			cordova.exec(function (result) {}, function (error) {}, "GATDevice", "exitApp", ["getdeviceId"]);
	}
}

// [WP]
function onBackConfirm(option) {
	if (option == 1) {
		cordova.exec(function (result) {}, function (error) {}, "GATDevice", "exitApp", ["getdeviceId"]);
	}
}

/*
	Check stack views and navigate to specific view
*/
function backAction(strKey) {
	var strFlag = '';
	if ((strKey == undefined) || (stackViews.length > 0 && strKey == stackViews[stackViews.length - 1]))
		strFlag = stackViews.pop();

	switch (strFlag) {
	case strCategory:
		{
			model.cateVM.viewCate();
			break;
		}
	case strSubCategory:
		{
			model.backToSubCate();
			break;
		}
	case strOverview:
		{
			model.backToOverview();
			break;
		}
	case strBookDetail:
		{
			model.displayBookDetail();
			break;
		}
	case strSettingBack:
		{
			model.viewSettings();
			break;
		}
	case strSettingStart:
		{
			model.hideSettingPopupPage();
			break;
		}
	case strSelectFolder: {
    	model.overviewVM.closeFolderPopup();
        break;
    }
	default:
		{}
	}
}

// Custom display popup message
function showPopupWithTitle(Title, Message, ButtonLabel) {
	navigator.notification.alert(
		Message,
		defaultCallback,
		Title,
		ButtonLabel
	);

	function defaultCallback() {}
}

// Custom display popup message
function showPopup(Message) {
	navigator.notification.alert(
		Message,
		defaultCallback,
		getLocalizeText('message'),
		getLocalizeText('ok')
	);

	function defaultCallback() {}
}

// Custom display popup message
function showPopupWithCallback(Message, callback) {
	navigator.notification.alert(
		Message,
		callback,
		getLocalizeText('message'),
		getLocalizeText('ok')
	);
}

function showLoadingDialog() {
	if (isShowLoading == true) {
		return;
	}
	$("body").append('<div class="modalWindow">' +
		'<div style="width: 20px; height: 20px; margin-left: 0px; margin-top: 0px; top: 50%; left: 50%; position: absolute;"></div>' +
		'</div>');
	spinner = new Spinner(optionLoading).spin();
	$(".modalWindow > div").append(spinner.el);
	isShowLoading = true;
}

function hideLoadingDialog() {
	isShowLoading = false;
	$(".modalWindow").remove();
	if (typeof (spinner.stop) != "undefined") {
		spinner.stop();
	}
	$.mobile.hidePageLoadingMsg();
}

/*
	[UNUSED] Show popup in the first times
*/
function showDescriptionStartPageFirstTime() {
	/* show alert first start app */
	var firstStart = localStore.get("firstStartNewAPI");
	if (firstStart == undefined) {
        /* clear all data if need */
        ResetLocalStorage();
        
//		showPopupWithTitle('', 'warning for data catch will be clear here, I need correct text and translatte it to all languages', getLocalizeText('ok'));
		localStore.save("firstStartNewAPI", true);
	}
}
function getDeviceId(){
    if (isWP) {
        cordova.exec(
                     function (resultString) {
                     var deviceId = resultString + "";
                     strDeviceId = hashCode(deviceId);
                     },
                     function (error) {},
                     "GATDevice",
                     "deviceUUID",
                     ["getdeviceId"]);
    } else {
        strDeviceId = device.uuid;
    }
}
function popFromStack(stack, strKey) {
        if (stack != undefined && stack.length != 0) {
            if (stack[stack.length - 1] == strKey) {
                stack.pop();
            }
        }
    }